

// global vars
var offersArray = [];

$(document).ready(drawCalendar);





/**
 * create the callendar
 */
function drawCalendar() {
	
	// render fullcalendar in the screen
	$('#calendar').fullCalendar({

		// --- General Display ---
		theme: 			true,
		selectable: 	true,	// Allows a user to highlight multiple days or timeslots by clicking and dragging.
		selectHelper: 	true,
		editable: 		true,	// edit events in the calendar
		weekends:		true,	// show hide weekends days
		allDaySlot:		false,	// dont display all-day option
		slotMinutes:	30,		// interval ... default is 30 minutes
		allDayDefault:	false,	// default value of the property 'allDay' from the object 'Event Obj'
		lazyFetching:	false,	// 'false' updates in every switch view, 'true' update only  when necessary
		defaultView:	'month',
		height:			450,
		aspectRatio:	2,
		timeFormat: 	{
			agenda:		'h:mm{ - h:mm}', 	// in agenda the event shcedule is shown in this format 5:00 - 6:30
			'':			'H:mm{-H:mm}'		// ... all others views
		},
		buttonText: 	{
			today: 		'hoje',
			month:		'mês',
			week:		'semana',
			day:		'dia'	
		},
		header: {
			left: 		'prev,next today',
			center: 	'title',
			right: 		'month,agendaWeek,agendaDay'
		},

		// --- clicking and hovering ---
		dayClick: 		function(date,allDay, jsEvent, view) { // ... when one cell is clicked
			
			// change the view when one single day is clicked in month view
			if (view.name != 'month') return;
			$('#calendar').fullCalendar('changeView', 'agendaDay');	
			$('#calendar').fullCalendar('gotoDate', date);
			
			
		},
		eventClick: 	function(event, element) {
			
			//console.group('group1');
			//console.dir(event);
			//console.groupEnd();
			//event.title = prompt('Title: ');
			//$('#calendar').fullCalendar('updateEvent',event);
		}, 
		eventMouseover: function(event, jsEvent, view) { // mouseover an event
			
		},
		eventMouseout: 	function(event, jsEvent, view) {
			
		},
		// -----------------------------

		// --- Draging and resizing events ---
		dragOpacity:		{agenda: .5, '': 0.7 },
		dragRevertDuration:	500,
		eventDragStart: 	function( event, jsEvent, ui, view) {
			console.log('eventDragStart');
			console.log(event);
		},
		eventDragStop:		function( event, jsEvent, ui, view) {
			console.log('eventDragStop');
			console.log(event);
		},
		eventDrop:			function( event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
			console.log('eventDrop');
		},
		eventResizeStart:	function( event, jsEvent, ui, view ) {
			console.log('eventResizeStart');
		},
		eventResizeStop: 	function( event, jsEvent, ui, view ) {
			console.log('eventResizeStop');
		},
		eventResize:		function( event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ) {
			console.log('eventResize');
		},

		// --- Selecting (... one or more fields) ---
		select: function(startDate, endDate, allDay, jsEvent, view) { // when a selection is maded

			// when the selection is maded in 'agendaDay' or 'agendaWeek' view
			if (view.name === 'agendaDay' || view.name === 'agendaWeek') {
				
				// current time in timestamp(millisecounds) format
				var now = new Date().getTime();
				
				// get available offer and show dialog with free offers 
				if ( now < startDate.getTime())
					getAvailableOffers(startDate, endDate);
			}
			
			// when the selection is maded in the 'monthView'
			else { 

			}
			
			//$('#calendar').fullCalendar('changeView', 'agendaWeek');	
			//$('#calendar').fullCalendar('gotoDate', startDate);
		},
		
		// --- Event Sources ---
		eventSources: [
		    {
				//url: 	'/eclipseWP/RadicalBooking/pt/School/staticEvents'
		    },
		    {
				url:	window.ajaxUrl + '/readEventAction'
		    },
		    {
				//url: 	'/eclipseWP/RadicalBooking/pt/School/tmp'
		    },
		    {
		    	/*
				events: [
					{
						id: 	'55',
						title:	'static02',
						start:	'2012-02-16 10:00:00',
						end:	'2012-02-16 11:00:00'
					}
				],
				color:		null,
				textColor:	'black'
				
				*/
		    }
		]
	});
}









/**
 *  send event data to be stored in the server
 */
function sendEvent(startDate, endDate) {
	
	$.ajax({
		//url:		'/eclipseWP/RadicalBooking/pt/School/createEventAction',
		url:		window.ajaxUrl + '/createEventAction',
		type:		'POST',		// type of request to make
		async:		true,		// asynchronous/synchronous request
		dataType:	"json",		// type of data returned from server
		
		// data to be sent to the server
		data:					
		{
			// getTime returns val in milliseconds ... convert to seconds (unixtimestamp)
			eventStart: 		startDate.getTime()/1000,	
			eventEnd:			endDate.getTime()/1000,
			offerName:			$("#offerList option:selected").text(),
			offerId:			$("#offerList option:selected").val()
		},

		// request was successful ... 'data' is received from server
		success: 	function(data, textStatus, jqXHR) {
			if (data.id===false) {
				// it wasnt possible to save that event
			}
			else {
				$('#calendar').fullCalendar('renderEvent',
				{
					id:		data.id,
					title:	data.title,
					start:	startDate,
					end:	endDate
				});
			}
		},

		// something went wrong ...
		error:		function(jqXHR, textStatus, errorThrown) {	
			$("#errorDialog").dialog(
				{
					width:		200,
					height:		150,
					show: 		'fade',
					hide: 		'fade',
					buttons: {

						"Ok": 		
						function() {
							$(this).dialog("close");
						}
					}
				}	
			);
		},
		
		// code to run regardless of success or failure
		complete: function(xhr, status) {
		}
	});
}










/**
 * Function to get available offers from server and to fill 
 * the select option box with those offers.
 * If there is no offers a message will be shown 
 */
function getAvailableOffers(startDate, endDate) {
	
	// global jquery function to get JSON (id,name,remainingClasses) file from the following server method
	$.getJSON(window.ajaxUrl + "/availableOffers", function(data) {
		// callback function ... here we put the code to be executed when the 'data' is received.
		// In this example is used an anonymous function. A reference to a function 
		// declaration could equally be provided as the callback
		
		//window.offersArray = null;
		
		// if no data is returned from server
		if (!data) {
			showNoOfferDialog();
		}
		else {
			//console.log(data);
			// ... data returned from the server?
			if (data.length !== 0) {
				// number of available classes for the first offer in the list
				$(".remainingClasses").html(data[0].remainingClasses);
				$(".numberOfClasses").html(data[0].numberOfClasses);
			}
			
			// ... holds data to be placed in the 'select' tag
			var options = '';
			
			for (var i = 0 ; i < data.length ; i++) {
				options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
			}
	
			// assign the data returned from the server to a global var
			// so these can be accessed in the 'offersDialog' (the data is passed by value)
			window.offersArray = data.slice();
			offers = data.slice();
			
			// put the values between the 'select' tags present inside the id selector 'offerList'
			$("select#offerList").html(options);
			
			showOfferDialog(startDate,endDate);
		}
	});
}


 
function showOfferDialog(startDate,endDate) {
	// create the dialog with a list of available offers
	$("#offersDialog").dialog(
		{
			//autoOpen: 	false,
			//overlay: { opacity: 0.2, background: "cyan" },
			width:		350,
			height:		250,
			//position: 	[420, 180],
			show: 		'fade',
			hide: 		'fade',
			buttons: {

				// send the data to be stored in the DB
				"Ok": 		
				function() {
					sendEvent(startDate, endDate);
					$(this).dialog("close");
				},

				// Operation canceled
				"Cancel": 	
				function() {
					$(this).dialog("close");
				}
			}
		}	
	);
}


function showNoOfferDialog() {
	
	$("#noOffers").dialog(
		{
			width:		350,
			height:		150,
			show: 		'fade',
			hide: 		'fade',
			buttons: {
				"Ok": 		
				function() {
					$(this).dialog("close");
				}
			}
		}	
	);
}


$(document).ready(function() {
		$("#offerList").change(function() {
			$(".remainingClasses").html(window.offersArray[this.selectedIndex].remainingClasses);
			$(".numberOfClasses").html(window.offersArray[this.selectedIndex].numberOfClasses);
		});
});











	